package com.example.study.controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.function.impl.ToString;
import com.example.study.commen.commenutils.CommonUtils;
import com.example.study.commen.email.EmailUtil;
import com.example.study.commen.print.CusUtils;
import com.example.study.commen.udp.UdpConfig;
import com.example.study.commen.websocket.WebSocketSever;
import com.example.study.config.JsonResult;
import com.example.study.config.ServerConfig;
import com.example.study.config.minio.MinioConfig;
import com.example.study.config.minio.MinioUtil;
import com.example.study.config.redis.RedisUtil;
import com.example.study.config.shiro.JwtUtil;
import com.example.study.config.shiro.NoAuthentication;
import com.example.study.manager_plus.mybatis_plus.entity.CameraInfo;
import com.example.study.manager_plus.mybatis_plus.entity.DeviceInfo;
import com.example.study.manager_plus.mybatis_plus.entity.WarnRule;
import com.example.study.manager_plus.mybatis_plus.service.DeviceInfoService;
import com.example.study.manager_plus.mybatis_plus.service.WarnRuleService;
import com.example.study.plus.mybatis_plus.entity.TokenUser;
import com.example.study.plus.mybatis_plus.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Operation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.integration.ip.udp.UnicastSendingMessageHandler;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import scala.Int;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

import com.example.study.manager_plus.mybatis_plus.service.CameraInfoService;

@RestController
@RequestMapping("/cum")
@Slf4j
@Api(description = "通用接口")
@CrossOrigin
public class StudyController {
    @Autowired
    private ServerConfig serverConfig;
    @Resource
    RedisUtil redisUtil;

    public String getIp() {
        return serverConfig.getIp();
    }

    @GetMapping("/test1")
    @ApiOperation(value = "获取端口号")
    @NoAuthentication
    public JsonResult<String> changePassword() {
        log.info(getIp() + "上线了");
        return new JsonResult<>("微服务" + getIp() + "上线了");
    }

    //    @ResponseBody
//    @RequestMapping(value = "/icon", method = RequestMethod.POST)
//    @ApiOperation("远程打印")
//    private JsonResult<String> saveIcon(@RequestParam MultipartFile icon, String printerName) throws Exception {
//        JsonResult<String> statusBean = new JsonResult<String>();
//        if (icon.getSize() > 0) {
//            String path = "C:\\Users\\15833\\Pictures\\Saved Pictures\\123";
////            String fileName = icon.getOriginalFilename();
//            System.out.println("name:"  printerName  "----"  icon.getName()  "______"  icon.getOriginalFilename());
//            File file = new File(path, System.currentTimeMillis()  icon.getOriginalFilename());
//            String fileSuffix = CusUtils.getFileSuffix(file);
//            System.out.println("Suffix:"  fileSuffix  "----path "  file.getAbsolutePath()  "   "  file.getCanonicalPath());
//            icon.transferTo(file);
//            if (fileSuffix.equals("docx")) {
//                String newPath=path  "\\123456"  System.currentTimeMillis()  ".pdf";
//                System.out.println("in  "  file.getPath()  "\nout  " newPath);
//                CusUtils.fileConversion(file.getPath(), newPath);
//
//                //调用打印机
//                statusBean.code = 200;
//                statusBean.message = "打印成功";
//                CusUtils.callPrinter(newPath,"NPI6FB127 (HP LaserJet P2055dn)");
//            } else if (fileSuffix.equals("jpg") || fileSuffix.equals("jpeg")) {
//                //调用打印机
//                statusBean.code = 200;
//                statusBean.message = "打印成功";
//                CusUtils.callPrinter(file.getPath(),"NPI6FB127 (HP LaserJet P2055dn)");
//            } else {
//                //返回类型失败
//                statusBean.code = 400;
//                statusBean.message = "打印失败，格式不正确，仅支持pdf,jpg,jpeg,docx";
//            }
////------其他数据库操作省略------
//
//
//        } else {
//            statusBean.code = 400;
//            statusBean.message = "没有收到文件";
//        }
//
//        return statusBean;
//    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    @PostMapping("/upload")
    @ApiOperation("文件上传测试")
    public JsonResult<String> upload(@RequestParam("file") MultipartFile multipartfile, HttpServletRequest request) {
        JsonResult<String> statusBean = new JsonResult<String>();
        String path = "C:\\Users\\15833\\Pictures\\Saved Pictures\\123";
        String format = sdf.format(new Date());
        File folder = new File(path);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldname = multipartfile.getOriginalFilename();
        String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."), oldname.length());
        try {
            File file = new File(folder, newname);
            multipartfile.transferTo(file);
            System.out.println(file.getAbsolutePath());//输出（上传文件）保存的绝对路径
            statusBean.data = file.getAbsolutePath() + newname;
            return statusBean;
        } catch (IOException e) {
            e.printStackTrace();
        }
        statusBean.message = "上传失败!";
        return statusBean;
    }


    /**
     * 给所有用户发消息
     *
     * @param message 消息
     * @return 给
     */
    @PostMapping("/message/send")
    @ApiOperation("给所有用户发消息")
    public JsonResult<String> sendAllMessage(@ApiParam("群发消息") @RequestParam String message) {
        Integer sent = WebSocketSever.sendAllMessage(message);
        return new JsonResult<>(sent == 0 ? "发送成功" : "发送失败");
    }

    @ApiOperation("向嵌入式发送udp数据")
    @PostMapping("/udp/send")
    public JsonResult<JSONObject> xx(@ApiParam("消息") @RequestParam("message") String information, @ApiParam("ip地址") @RequestParam("ip") String ip) {

        byte[] bytes = information.getBytes(StandardCharsets.UTF_8);
        UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler(ip, UdpConfig.getSendingPort());
        handler.handleMessage(MessageBuilder.withPayload(bytes).build());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("目标地址", ip);
        jsonObject.put("目标端口号", UdpConfig.getSendingPort());
        jsonObject.put("UDP信息", information);
        return new JsonResult<>(jsonObject);
    }

    @Autowired
    CameraInfoService cameraInfoService;
    @Autowired
    DeviceInfoService deviceInfoService;


    @ApiOperation("解析桌面文件")
    @PostMapping("/udp/test1")
    public JsonResult<JSONObject> zzz() {

        //            cameraInfo.setCameraProductName("京东云智能云台摄像头");
        //            cameraInfo.setCommissioner("京东科技信息技术有限公司");
        //            cameraInfo.setManufacturer("深圳市瀚晖威视科技有限公司");
        //            cameraInfo.setExternalModel("HHK-3209H-M/IPC-G5A1D0F2-HK");
        //            cameraInfo.setWifiBand("2.4GHz");
        //            cameraInfo.setWifiProtocol("IEEE 802.11b/g/n");
        //            cameraInfo.setMacAddress("002A2B4BE5B9");
        //            cameraInfo.setDefaultSsid("");
        //            cameraInfo.setSn("设备License JDH032091abn54z5");
        //            cameraInfo.setBarCode("，100074420499");

        //            cameraInfo.setUseApp();
        //            cameraInfo.setUnsupportedWebLogin();
        //            cameraInfo.setWarrantyCardIncluded();


        //            cameraInfoService.saveData(cameraInfo);


        String
                filePath = "C:/Users/206/Desktop/后台2/副本wifi网络摄像头品类信息(6.5）.xlsx"; // 替换为你的Excel文件路径
        List<String[]> data = new ArrayList<>();

        try (FileInputStream fileInputStream = new FileInputStream(new File(filePath))) {
            Workbook workbook = new XSSFWorkbook(fileInputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个sheet

            // 遍历行
            for (Row row : sheet) {
                String[] rowData = new String[row.getLastCellNum()];
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    rowData[i] = getCellValue(cell);

                }
                data.add(rowData);

            }

            // 打印数据
            for (int i = 0; i < data.size(); i++) {
                String[] row = data.get(i);
                CameraInfo cameraInfo = new CameraInfo();
                cameraInfo.setId((long) i);
                cameraInfo.setCameraProductName(row[0]);
                cameraInfo.setCommissioner(row[1]);
                cameraInfo.setManufacturer(row[2]);
                cameraInfo.setExternalModel(row[3]);
                cameraInfo.setWifiBand(row[4]);
                cameraInfo.setWifiProtocol(row[5]);
                cameraInfo.setMacAddress(row[6]);
                cameraInfo.setDefaultSsid(row[7]);
                cameraInfo.setSn(row[8]);
                cameraInfo.setBarCode(row[9]);
                //                B8CC5F122686
                //                for (int i = 0; i < row.length; i) {
                //
                //                    log.info("第{}列数据：{}", i, row[i]);
                //                }
                //            cameraInfo.setCameraProductName("京东云智能云台摄像头");
                //            cameraInfo.setCommissioner("京东科技信息技术有限公司");
                //            cameraInfo.setManufacturer("深圳市瀚晖威视科技有限公司");
                //            cameraInfo.setExternalModel("HHK-3209H-M/IPC-G5A1D0F2-HK");
                //            cameraInfo.setWifiBand("2.4GHz");
                //            cameraInfo.setWifiProtocol("IEEE 802.11b/g/n");
                //            cameraInfo.setMacAddress("002A2B4BE5B9");
                //            cameraInfo.setDefaultSsid("");
                //            cameraInfo.setSn("设备License JDH032091abn54z5");
                //            cameraInfo.setBarCode("100074420499");


                cameraInfoService.saveData(cameraInfo);

            }


        } catch (IOException e) {
            e.printStackTrace();

        }


        return new JsonResult<>();

    }


    private static String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {

            case STRING:
                return cell.getStringCellValue();

            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue());

            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());

            case FORMULA:
                return cell.getCellFormula();

            default:
                return "";

        }

    }

    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private MinioConfig prop;

    @Operation(summary = "文件上传返回url")
    @PostMapping("/minio/upload")
    public JsonResult<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) {
        String objectName = minioUtil.upload_originalName(file);
        if (null != objectName) {
            Map<String, Object> ret = new HashMap<>();
            ret.put("url", prop.getEndpoint() + "/" + prop.getBucketName() +
                    "/" + objectName);
            return new JsonResult<>(ret);
        }
        return new JsonResult<>(300, "上传失败");
    }


    @Operation(summary = "文件上传解析")
    @PostMapping("/minio/uploadAndAnalysis")
    public JsonResult<String> uploadAndAnalysis(@RequestParam("file") MultipartFile image) {
        //获取原始文件名
        String originalFilename = image.getOriginalFilename();

        //构建新的文件名
//        String extname = originalFilename.substring(originalFilename.lastIndexOf("."));//文件扩展名
//        String newFileName = UUID.randomUUID().toString()+extname;//随机名+文件扩展名

        //将文件存储在服务器的nginx目录下，这里是随便写的地址
        try {
            File file = new File("D:/home/java/files/" + originalFilename);
            image.transferTo(file);
//            CommonUtils.parsingFiles(file);
        } catch (IOException e) {
            return new JsonResult<>(300, e.toString());
        }

        return new JsonResult<>(200, "上传成功");

    }

    @ApiOperation("查询全部数据")
    @PostMapping("/queryAllData")
    public JsonResult<List<CameraInfo>> queryAllData() {
        List<CameraInfo> cameraInfos = cameraInfoService.queryAllData();
        return new JsonResult<>(cameraInfos);
    }


    @ApiOperation("录入办公设备桌面文件")
    @PostMapping("/udp/test2")
    public JsonResult<JSONObject> yyy() {


        String
                filePath = "C:/Users/206/Desktop/后台2/办公网络设备信息.xlsx"; // 替换为你的Excel文件路径
        List<String[]> data = new ArrayList<>();

        try (FileInputStream fileInputStream = new FileInputStream(new File(filePath))) {
            Workbook workbook = new XSSFWorkbook(fileInputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个sheet

            // 遍历行
            for (Row row : sheet) {
                String[] rowData = new String[row.getLastCellNum()];
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    rowData[i] = getCellValue(cell);

                }
                data.add(rowData);

            }

            // 打印数据
            for (int i = 0; i < data.size(); i++) {
                String[] row = data.get(i);

                DeviceInfo deviceInfo = new DeviceInfo();
//                deviceInfo.setId((long) i);
                deviceInfo.setHostName(row[0]);
                deviceInfo.setMacVendor(row[1]);
                deviceInfo.setDeviceModel(row[2]);
                deviceInfo.setMacAddress(row[3]);
                deviceInfo.setIpAddress(row[4]);
                if (row[0].contains("电脑")) {
                    deviceInfo.setDeviceType("电脑");
                } else if (row[0].contains("手机")) {
                    deviceInfo.setDeviceType("手机");
                } else if (row[0].contains("摄像")) {
                    deviceInfo.setDeviceType("摄像头");
                } else {
                    deviceInfo.setDeviceType("通用");
                }
                deviceInfoService.saveData(deviceInfo);
            }


        } catch (IOException e) {
            e.printStackTrace();

        }


        return new JsonResult<>();

    }


    @ApiOperation("查询设备详情全部数据")
    @PostMapping("/queryAllData2")
    public JsonResult<List<DeviceInfo>> queryAllDataw() {
        List<DeviceInfo> deviceInfos = deviceInfoService.queryAll();
        return new JsonResult<>(deviceInfos);
    }

    @Autowired
    WarnRuleService warnRuleService;
    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation("查询全部摄像头")
    @PostMapping("/queryCamera")
    public JsonResult<List<CameraInfo>> queryCamera() {
        List<CameraInfo> cameraInfos = cameraInfoService.queryAllData();
        for (CameraInfo cameraInfo : cameraInfos) {
            String macAddress = cameraInfo.getMacAddress();
            String s = formatMacAddress(macAddress);

            if (s.length() >= 10) {
                String substring = s.substring(0, 8);
                log.info("lufeixxx: " + substring);
                UAVBean uavBean = new UAVBean(substring, "192.168.110.1", cameraInfo.getManufacturer());
                droneCharging1(restTemplate, uavBean);
            }
        }

        return new JsonResult<>(cameraInfos);


          }

    public static String formatMacAddress(String macAddress) {
        // Insert a colon (:) after every two characters
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < macAddress.length(); i += 2) {
            if (i > 0) {
                sb.append(":");
            }
            sb.append(macAddress.substring(i, Math.min(i + 2, macAddress.length())));
        }
        // Convert to lowercase
        return sb.toString().toLowerCase();
    }

//        private final String notifyDrones = "http://check.dstckj.com/api/v1/warn/add";       //通知无人机接口全地址
//    private final String notifyDrones = "http://122.114.61.101:8181/api/v1/warn/add";
    private final String notifyDrones = "http://127.0.0.1:8181/api/v1/warn/add";

    public JsonResult<String> droneCharging1(RestTemplate restTemplate, UAVBean uavBean) {
        try {
            // 发起POST请求
            ResponseEntity<JsonResult> responseEntity = restTemplate.postForEntity(notifyDrones, uavBean, JsonResult.class);

            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                log.info("无人机通知接口返回:{}", responseEntity.getBody());
                return responseEntity.getBody();
            } else {
                return new JsonResult<>(300, responseEntity.toString());
            }
        } catch (Exception e) {
            log.info("无人机通知接口返回:{}", e.getMessage());
            return new JsonResult<>(300, e.getMessage());
        }
//        return new JsonResult<>(200, "暂时注释，方便调试程序 ");
    }

    //{
//  "macPrefix": "78:DF:72",
//  "ip": "192.168.110.1",
//  "remark":"1"
//}
    @Data
    class UAVBean {
        public String macPrefix;
        public String ip;
        public String remark;

        public UAVBean(String macPrefix, String ip, String remark) {
            this.macPrefix = macPrefix;
            this.ip = ip;
            this.remark = remark;
        }
    }
}
